<?php
namespace Home\Controller;
use Think\Controller;

/* 访问控制 */
defined('IN_ECTOUCH') or die('Deny Access');

class FlowController extends CommonController {

    protected $user_id=0;
    protected $info;
    /**
     * 构造函数
     */
    public function __construct() {


        // $str='user_id=17';
        // $token=M('users')->where($str)->getField('token');
        // $_POST['token']=$token;

        parent::__construct();


       $this->info=$this->common_info;
       $this->check_login();

    }

    private function check_login() {
        //检测是否登录 token是否过期
        $Users=D('Users');
        $token=I('post.token');
        
        
        $info=$this->info;

        if(!$info['user_id'])return_data(20000,'需要先登录',$_POST);
        else
        {
            $this->info=$info;
            $this->user_id=$info['user_id'];
        }

     }


      //获取用户可用 红包列表
      private function get_use_bonus($price=0)
      {         
            /*************测试数据********************开始***/
            // $_POST['total_price']=200;
            //  print_r(json_encode($_POST));exit();
            /*************测试数据********************结束***/
            // $total_price=I('post.total_price',0,'int');
            $order_price=$price?$price:0;

            /* 如果使用红包，取得用户可以使用的红包及用户选择的红包 */
            $user_bonus=array();
            $is_use_bonus = M('shop_config')->where("code='use_bonus'")->getField('value');
            if ($is_use_bonus) {
                // 取得用户可用红包
                $user_bonus = D('order')->user_bonus($this->user_id,$order_price);
                if (!empty($user_bonus)) {
                    foreach ($user_bonus as $key => $val) {
                        // $user_bonus [$key] ['bonus_money_formated'] = price_format($val ['type_money'], false);
                        $user_bonus[$key]['img_type_money']=round(floor($val ['type_money']),0);//向下四舍五入

                    }

                     
                }
            }
           
            return  $user_bonus;
      }
     

    /**
     * 购物车列表
     */
    public function index() {

      // print_r($this->info);exit();
        
        //更新购物车
        D('users')->recalculate_price($this->info);

        $list=D('order')->get_cart_goods($this->info);
        if($list)return_data(0,'显示购物车成功',$list);
        else return_data(0,'购物车为空');
      }
      /**
     * 更新 购物车
     */
    public function update_cart() {
        /*************测试数据********************开始***/
        // $_POST['rec_id']='5261';
        // $_POST['buy_num']='11';
        // $_POST['attr_id']=array('95','98');   
        // $_POST['attr_id']=array('96','97');  

        //  print_r(json_encode($_POST));exit();
        /*************测试数据********************结束***/

        $rec_id=I('post.rec_id',0,'int');
        $buy_num=I('post.buy_num',1,'int');
        $product_spec=I('post.attr_id','');

        $user_id=$this->user_id;
        $DB_PREFIX=C('DB_PREFIX');

        $cart_info=M('cart')->field("goods_id,product_id,goods_attr_id,goods_number")->where("rec_id='$rec_id' and user_id='$user_id'")->find();
        // print_r(M()->getlastsql());exit();
        if(!$cart_info)return_data(20002,"你的购物车没有该商品记录");

        $goods_id=$cart_info['goods_id'];
        $product_old_id=$cart_info['product_id'];
        $goods_attr_id=$cart_info['goods_attr_id'];
        $goods_number=$cart_info['goods_number'];

        $is_same=0;//是否没有改变属性
        if($product_spec)
        {
          $diff=0;
          foreach ($product_spec as $key => $value) {
            $find=strstr($goods_attr_id, $value);
            if($find)$diff++;
          }

          if($diff==count($product_spec))$is_same=1;

        }

        // print_r($diff);exit();
        //购物车商品没有更改
        if($buy_num==$goods_number&&$is_same)
          return_data(0,'商品更新成功');


      // 检查：如果商品有规格，而post的数据没有规格，则报错
        if (empty($product_spec)) {
  
            $sql = "SELECT  " . " g.goods_attr_id " 
            . 'FROM ' . $DB_PREFIX . 'goods_attr AS g ' 
            . 'LEFT JOIN ' . $DB_PREFIX . 'attribute AS a ON a.attr_id = g.attr_id '
             . "WHERE a.attr_type != 0 AND g.goods_id = '" 
             . $goods_id . "' " . ' limit 1 ';
            $res = M()->query($sql);
            if (!empty($res)) {
                return_data(20001,'该商品存在属性，不可为空');
            }
        }
        else
        {
          //查询货品的信息
           $product_info = D('ProductsBase')->get_products_info($goods_id, $product_spec);
           if($product_info)
           {
             $product_id=$product_info['product_id'];

             //检测购物车是否有该商品
             if($product_id!=$product_old_id)
             {
                $is_same_cart=M("cart")->where("goods_id='$goods_id' and product_id='$product_id' and user_id='$user_id' and rec_id!='$rec_id'")->getField("rec_id");
                if($is_same_cart)return_data(20002,'您的购物车已有该商品，请对它进行修改');
             }
            
           }
           else //规格是否合法
           {
               //attr_type = 1（单选）时才可判断搜索goods_id
               // $spec_goods_id=D('GoodsBase')->is_goods_spec($product_spec);
               // if($spec_goods_id!=$goods_id)return_data(20002,'属性ID集合不合法');

               //检测购物车是否有该商品
                $spec_name=D('order')->get_goods_attr_info($product_spec);
                $is_same_cart=M("cart")->where("goods_id='$goods_id' and goods_attr='$spec_name' and user_id='$user_id' and rec_id!='$rec_id'")->getField("rec_id");
                if($is_same_cart)return_data(20002,'您的购物车已有该商品，请对它进行修改');
           }
        }


        // 查询：系统启用了库存，检查输入的商品数量是否有效
        // 查询
        $arrGoods =D('goods')->field('goods_name,goods_number,extension_code')->where('goods_id =' . $goods_id)->find();
       
        if ($arrGoods ['extension_code'] != 'package_buy') {
             //库存判断
             if($product_info&&$product_info['product_number']<$buy_num)return_data(50002,'货品库存不足，请选择其他属性');
             else if ($arrGoods ['goods_number'] < $goodsnmber) {

                  return_data(50001,'商品库存不足');
             }
        }

  

        // 更新：购物车
        $re=D('Order')->updateto_cart($this->info,$goods_id, $buy_num, $product_spec, $rec_id);

// print_r($re);exit();
        if (!$re['code']) {
          return_data(0, $re['mes']);
        } else {
           return_data($re['code'],$re['mes']);
        }

      
      }     
        /**
     * 删除 购物车
     */
    public function del_cart() {
        /*************测试数据********************开始***/
        // $_POST['rec_ids']=array('5229','5232');
        // $_POST['is_all']=0;     

        //  print_r(json_encode($_POST));exit();
        /*************测试数据********************结束***/

        $rec_ids=I('post.rec_ids','');
        $is_all=I('post.is_all',0,'int');

          if($rec_ids&&!is_array($rec_ids))
          {
            $rec_ids=explode(',', $rec_ids);
          }


        if($is_all)
        {
          $where['user_id']=$this->user_id;
          $status=M('cart')->where($where)->delete();
        }
        else if($rec_ids)
        {
          
          $where="user_id='$this->user_id' and rec_id ".db_create_in($rec_ids);
          $status=M('cart')->where($where)->delete();
        }
        if($status)return_data(0,'购物车删除成功',$status);
        else return_data(20002,'购物车删除失败',array());

      
      }     

     /**
     * 放入购物车
     */
    public function add_to_cart() {
      /*************测试数据********************开始***/
      // $_POST['id']='7';
      // $_POST['buy_num']='5';
      // $_POST['attr_id']=array('60','58');
      

       // print_r(json_encode($_POST));exit();
      /*************测试数据********************结束***/

          $goods_id=I('post.id',0);
          $buy_num=I('post.buy_num',1,'int');//商品数量
          $product_spec=I('post.attr_id','');//属性集合
          // $parent=I('post.parent',0,'int');//作为购物的配件

          if($product_spec&&!is_array($product_spec))
          {
            $product_spec=explode(',', $product_spec);
          }

          $parent=0;
          

          $DB_PREFIX=C('DB_PREFIX');
          $user_id=$this->user_id;



          if (empty($goods_id)) {
              return_data(20001,'商品ID没有传递');
          }


        // 初始化返回数组
        $result = array(
            'error' => 0,
            'message' => '',
            'content' => '',
            'goods_id' => '',
            'product_spec' => ''
        );



        // 检查：如果商品有规格，而post的数据没有规格，则报错
        $product_id=0;
        if (empty($product_spec)) {
  
            $sql = "SELECT a.attr_id, a.attr_name, a.attr_type, " . "g.goods_attr_id, g.attr_value, g.attr_price " 
            . 'FROM ' . $DB_PREFIX . 'goods_attr AS g ' 
            . 'LEFT JOIN ' . $DB_PREFIX . 'attribute AS a ON a.attr_id = g.attr_id '
             . "WHERE a.attr_type != 0 AND g.goods_id = '" 
             . $goods_id . "' " . 'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id';
            $res = M()->query($sql);
            if (!empty($res)) {
                $spe_arr = array();
                foreach ($res as $row) {
                    $spe_arr [$row ['attr_id']] ['attr_type'] = $row ['attr_type'];
                    $spe_arr [$row ['attr_id']] ['name'] = $row ['attr_name'];
                    $spe_arr [$row ['attr_id']] ['attr_id'] = $row ['attr_id'];
                    $spe_arr [$row ['attr_id']] ['values'] [] = array(
                        'label' => $row ['attr_value'],
                        'price' => $row ['attr_price'],
                        'format_price' => price_format($row ['attr_price'], false),
                        'id' => $row ['goods_attr_id']
                    );
                }
                $i = 0;
                $spe_array = array();
                foreach ($spe_arr as $row) {
                    $spe_array [] = $row;
                }
                $result ['error'] = '商品规格存在，但没有传递参数';
                $result ['goods_id'] = $goods_id;
                $result ['parent    '] = $parent;
                $result ['message'] = $spe_array;

                return_data(20002,$result ['error']);
            }
        }
        else
        {
          //查询货品的信息
           $product_info = D('ProductsBase')->get_products_info($goods_id, $product_spec);
           $product_id=0;
           if($product_info)
           {
            $product_id=$product_info['product_id'];
            
           }
           else //规格是否合法
           {
                //attr_type = 1（单选）时才可判断搜索goods_id
               // $spec_goods_id=D('GoodsBase')->is_goods_spec($product_spec);
               // if($spec_goods_id!=$goods_id)return_data(20002,'属性ID集合不合法');
           }
        }


        // 查询：系统启用了库存，检查输入的商品数量是否有效
        // 查询
        $arrGoods =D('goods')->field('goods_name,goods_number,extension_code')->where('goods_id =' . $goods_id)->find();

        $goodsnmber = D('Users')->get_goods_number($user_id,$goods_id,$product_id);

        $goodsnmber+=$buy_num;

       
        if ($arrGoods ['extension_code'] != 'package_buy') {
             //库存判断
             if($product_info&&$product_info['product_number']<$buy_num)return_data(50002,'货品库存不足，请选择其他属性');
             else if ($arrGoods ['goods_number'] < $goodsnmber) {

                  return_data(50001,'商品库存不足');
             }
        }

  

        // 更新：添加到购物车
        $re=D('Order')->addto_cart($this->info,$goods_id, $buy_num, $product_spec, $parent);

        if (!$re['code']) {
          return_data(0,'加入购物车成功');
        } else {
           return_data($re['code'],$re['mes']);
        }
        


    }

     /**
     * 订单确认
     */
    public function checkout() {

       /*************测试数据********************开始***/



       //立即购买
      // $_POST['id']='15';
      // $_POST['buy_num']='4';
      // $_POST['attr_id']=array('97','95');


      
       //购物车购买
       // $_POST['rec_ids']=array('5279','5280','5281');
       // print_r(json_encode($_POST));exit();

       
      /*************测试数据********************结束***/


          $user_id=$this->user_id;
          $flow_type=0;
          $DB_PREFIX=C('DB_PREFIX');
          $order=array(
             'shipping_fee'=>price_format(0)
          );//订单信息


         /**********************一键购买***************开始****/
          $goods_id=I('post.id',0);
          if($goods_id)
          {
            $buy_num=I('post.buy_num',1,'int');//商品数量
            $attr_id_arr=I('post.attr_id','');//属性集合
             if($attr_id_arr&&!is_array($attr_id_arr))
              {
                $attr_id_arr=explode(',', $attr_id_arr);
              }


            $goods = D('Goods')->get_goods_info($goods_id,$this->info);

            //规格价格
            $spec_price=0;
            $post=array();//检测规格，提交订单时使用
            $spec_name="";
             //库存判断
            if($goods['goods_number']<$buy_num)return_data(50001,'商品库存不足');
            else if($attr_id_arr)
            {

               $product_info = D('ProductsBase')->get_products_info($goods_id, $attr_id_arr);
               
               if($product_info)
               {
                 //库存判断
                 if($product_info['product_number']<$buy_num)return_data(50002,'货品库存不足，请选择其他属性');
               }
              //属性名称
              if($attr_id_arr)
              {
              	$spec_name=D('order')->get_goods_attr_info($attr_id_arr); 
              	$spec_price=D('Goods')->spec_price($attr_id_arr);
              }
                            
            }
            else
            {

  
                $sql = "SELECT a.attr_id, a.attr_name, a.attr_type, " . "g.goods_attr_id, g.attr_value, g.attr_price " 
                . 'FROM ' . $DB_PREFIX . 'goods_attr AS g ' 
                . 'LEFT JOIN ' . $DB_PREFIX . 'attribute AS a ON a.attr_id = g.attr_id '
                 . "WHERE a.attr_type != 0 AND g.goods_id = '" 
                 . $goods_id . "' " . 'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id';
                 $res = M()->query($sql);
                if (!empty($res)) {
                    // $spe_arr = array();
                    // foreach ($res as $row) {
                    //     $spe_arr [$row ['attr_id']] ['attr_type'] = $row ['attr_type'];
                    //     $spe_arr [$row ['attr_id']] ['name'] = $row ['attr_name'];
                    //     $spe_arr [$row ['attr_id']] ['attr_id'] = $row ['attr_id'];
                    //     $spe_arr [$row ['attr_id']] ['values'] [] = array(
                    //         'label' => $row ['attr_value'],
                    //         'price' => $row ['attr_price'],
                    //         'format_price' => price_format($row ['attr_price'], false),
                    //         'id' => $row ['goods_attr_id']
                    //     );
                    // }
                    // $i = 0;
                    // $spe_array = array();
                    // foreach ($spe_arr as $row) {
                    //     $spe_array [] = $row;
                    // }
                    // $result ['goods_id'] = $goods_id;
                    // $result ['parent'] = 0;
                    // $result ['message'] = $spe_array;

                    return_data(20002,'商品规格存在，但没有传递参数');
                }
        
            }
            




            //收货地址判断
            $address=D('order')->get_my_address($user_id);

            // if(!$address)return_data(50000,'收货地址为空');//去添加收货地址

            $order['address_id']=$address['address_id']?$address['address_id']:0;

            $order['order_address']['consignee']='';
            $order['order_address']['mobile_phone']='';
            $order['order_address']['address']='';
            if($address)
            {
                //计算费用
                  $addr_ids=array(
                      $address['country'],
                      $address['province'],
                      $address['city'],
                      $address['district']
                    );
                   $shipping_list=D('order')->available_shipping_list($addr_ids);

                  //收货区域
                  $address['province']=D('RegionBase')->get_region_name($address['province']);
                  $address['city']=D('RegionBase')->get_region_name($address['city']);
                  $address['district']=D('RegionBase')->get_region_name($address['district']);

                  //所有快递
                 // foreach ($shipping_list as $key => $val) {
                 //      // 兼容过滤ecjia配送方式
                 //      if (substr($val['shipping_code'], 0 , 5) == 'ship_') {
                 //          unset($shipping_list[$key]);
                 //      }
                 //      $shipping_cfg = unserialize_config($val ['configure']);


                 //      $shipping_fee=shipping_fee($val['shipping_code'], unserialize($val ['configure']), $goods ['goods_weight']*$buy_num, $goods ['goods_price']*$buy_num, $buy_num);
                 //      $shipping_fee = ($goods ['is_shipping'] == 1) ? 0 :$shipping_fee ;
                    
                 //      // $shipping_list [$key] ['format_shipping_fee'] = price_format($shipping_fee, false);
                 //      $shipping_list [$key] ['shipping_fee'] = $shipping_fee;
                 //      // $shipping_list [$key] ['free_money'] = price_format($shipping_cfg ['free_money'], false);
                 //      // $shipping_list [$key] ['insure_formated'] = strpos($val ['insure'], '%') === false ? price_format($val ['insure'], false) : $val ['insure'];

                 //      /* 当前的配送方式是否支持保价 */
                 //      // if ($val ['shipping_id'] == $order ['shipping_id']) {
                 //      //     $insure_disabled = ($val ['insure'] == 0);
                 //      //     $cod_disabled = ($val ['support_cod'] == 0);
                 //      // }
                 //  }
                 //  //默认 自定义快递
                 //  if($shipping_list [0] ['shipping_fee'])
                 //  $shipping_fee=$shipping_list [0] ['shipping_fee'];

                  //快递费用 
                  $shipping_id=8; //默认   
                  if ($shipping_id > 0) {
                    $region= $addr_ids;

                    $shipping_info = D('order')->shipping_area_info($shipping_id, $region);                

                    if (!empty($shipping_info)) {
                        $shipping_fee = ($goods ['is_shipping'] == 1) ? 0 : shipping_fee($shipping_info['shipping_code'], $shipping_info['configure'], $goods['goods_weight']*$buy_num,  $goods ['goods_price']*$buy_num, $buy_num);

                    }
                   }



                  $order['order_address']['consignee']=$address['consignee'];
                  $order['order_address']['mobile_phone']=$address['mobile'];
                  $order['order_address']['address']=$address['province'].$address['city'].$address['district'].$address['address'];
            }

          

            $order['shipping_fee']=$shipping_fee?$shipping_fee:0;

            
            $goods['spec_name']=$spec_name;

            //处理显示的商品信息

            $order_goods['id']=$goods['id'];
            $order_goods['name']=$goods['name'];
            $order_goods['format_goods_price']= price_format($goods['goods_price']+$spec_price);
            $order_goods['goods_img']=$goods['goods_img'];
            $order_goods['buy_num']=$buy_num;
            $order_goods['spec_name']=$spec_name;
            $order_goods['formated_subtotal']=price_format(($goods['goods_price']+$spec_price)*$buy_num);
            // $order_goods['spec_price']=$spec_price;

  
            $order['order_goods'][]=$order_goods;
            $order['total_price']=($goods['goods_price']+$spec_price)*$buy_num+$shipping_fee;
            $order['format_total_price']=price_format($order['total_price']);

            $order['attr_id']=$attr_id_arr;
            $order['total_number']=$buy_num;

            //红包列表
            $use_bonus=$this->get_use_bonus( $order['total_price']);
            $order['use_bonus']=$use_bonus?$use_bonus:array();

            //红包处理

        // if (!empty($order['bonus_id'])) {
        //     $bonus = D('Order')->bonus_info($order['user_id'],$order['bonus_id']);
        //     $total['bonus'] = $bonus['type_money'];
        // }
        // $total['bonus_formated'] = price_format($total['bonus'], false);

        // /* 线下红包 */
        // if (!empty($order['bonus_kill'])) {
        //     $bonus = D('Order')->bonus_info(0, $order['bonus_kill']);
        //     $total['bonus_kill'] = $order['bonus_kill'];
        //     $total['bonus_kill_formated'] = price_format($total['bonus_kill'], false);
        // }
            
            return_data(0,'确认订单显示成功',$order);exit;



          }
          /**********************一键购买***************结束****/
          else//购物车
          {
            $rec_ids=I('post.rec_ids','');

             if($rec_ids&&!is_array($rec_ids))
              {
                $rec_ids=explode(',', $rec_ids);
              }

            /* 检查购物车中是否有商品 */
            if(!empty($rec_ids))
              $condition = "user_id = '" . $user_id . "' " . "AND parent_id = 0 AND is_gift = 0 AND rec_type = '$flow_type' AND rec_id ".db_create_in($rec_ids);
            else
              return_data(20002,'rec_ids没有参数');
           
            $count =M('cart')->where($condition)->count();



            
            if($count==0)
            {
              return_data(50003,'购物中没有商品');
            }

            // 取得商品列表，计算合计
            $cart_goods = D('Order')->cart_goods($this->info,$flow_type,$rec_ids);
            if(!$cart_goods)return_data(20002,'购物车读取不合法');


            // 取得订单信息
            $order = D('Order')->flow_order_info();


            $order['address_id']=$address['address_id']?$address['address_id']:0;

            $order['order_address']['consignee']='';
            $order['order_address']['mobile_phone']='';
            $order['order_address']['address']='';
            //收货地址判断
            $address=D('order')->get_my_address($user_id);
            if($address)
            {
               //收货区域
              $consignee['province']=D('RegionBase')->get_region_name($address['province']);
              $consignee['city']=D('RegionBase')->get_region_name($address['city']);
              $consignee['district']=D('RegionBase')->get_region_name($address['district']);

              $order['order_address']['consignee']=$address['consignee'];
              $order['order_address']['mobile_phone']=$address['mobile'];
              $order['order_address']['address']=$consignee['province'].$consignee['city'].$consignee['district'].$address['address'];
            }

            // if(!$address)return_data(50000,'收货地址为空');//去添加收货地址


            //计算订单的费用
            $total = D('Users')->order_fee($this->info,$order, $cart_goods, $address);
            

            //返回数据处理
            $new_order['rec_ids']=$rec_ids;
            $new_order['shipping_fee']=$total['shipping_fee'];
            $new_order['format_total_price']=$total['amount_formated'];
            $new_order['total_price']=$total['amount'];
            $new_order['total_number']=$total['real_goods_count'];

            // $new_order['bonus']=$total['bonus'];

           /* 取得可以得到的积分和红包 */
            // $total_integral= D('Order')->cart_amount($rec_ids,false, $flow_type) - $total ['bonus'] - $total ['integral_money']);
            // $total_integral=$total['will_get_bonus'];


            foreach ($cart_goods as $key => $value) {
              $new_goods[$key]['id']=$value['goods_id'];
              $new_goods[$key]['name']=$value['goods_name'];
              $new_goods[$key]['format_goods_price']=$value['formated_goods_price'];
              $new_goods[$key]['goods_img']=$value['goods_img'];
              $new_goods[$key]['buy_num']=$value['goods_number'];
              $new_goods[$key]['spec_name']=$value['goods_attr'];
              $new_goods[$key]['formated_subtotal']=$value['formated_subtotal'];
            }

            $new_order['order_goods']=$new_goods;
            $new_order['order_address']=$order['order_address'];

             //红包列表
            $use_bonus=$this->get_use_bonus( $new_order['total_price']);
            $new_order['use_bonus']=$use_bonus?$use_bonus:array();

            return_data(0,'确认订单显示成功',$new_order);
          }
            

          

      
    }
    /**
     * 生成订单
     */
    public function done() {
  /*************测试数据********************开始***/


      // $_POST['id']='8';
      // $_POST['buy_num']='2';
      // $_POST['attr_id']=array('92','93');

      // $_POST['buy_mes']='颜色不要错了';
      
        //购物车购买
        // $_POST['rec_ids']=array('5271','5241','5242');

        //红包
        // $_POST['bonus_id']=10;
    
       // print_r(json_encode($_POST));exit();
      /*************测试数据********************结束***/
          /* 取得购物类型 */
          $flow_type =0;
          // $rec_ids= I('post.rec_ids',0);



          $user_id=$this->user_id;          
          $mshop_id=$this->info['mshop_id'];
          $mshop_id= $mshop_id? $mshop_id :0;

          $DB_PREFIX=C('DB_PREFIX');
          $M_order_info=M('order_info');
          $M_order_goods=M('order_goods');
          $M_goods=M('goods');
          $M_products=M('products');

          // 订单信息
           $order = array(
            'shipping_id' =>8,//快递ID
            'pay_id' => 0, // 付款方式
            'pack_id' => 0,
            'card_id' =>0,
            // 'card_message' => trim($_POST ['card_message']),
            'surplus' =>0,
            'integral' =>0,
            'bonus_id' => I('post.bonus_id',0,'int'),
            'need_inv' =>0, //是否能开发票
            // 'inv_type' => $_POST ['inv_type'],
            // 'inv_payee' => trim($_POST ['inv_payee']),
            // 'inv_content' => $_POST ['inv_content'],
            'postscript' => I('post.buy_mes',''),//留言
            'how_oos' => '等待所有商品备齐后再发',
            'need_insure' =>0, //是否需要保价
            'user_id' => $user_id,
            'add_time' => gmtime(),
            'order_status' => 1,
            'shipping_status' =>0,
            'pay_status' =>0,
            'agency_id' =>0,//查询配送区域属于哪个办事处管辖
            'mobile_order' => 2,
            'mobile_pay' => 2,
            'mshop_id' => $mshop_id
        );
        /* 扩展信息 $_SESSION ['flow_type']*/
        $order ['extension_code'] = '';
        $order ['extension_id'] = 0;




         /* 订单中的商品 */

        /* 配送方式 */
        if ($order ['shipping_id'] > 0) {
            $shipping = D('order')->shipping_info($order ['shipping_id']);
            $order ['shipping_name'] = addslashes($shipping ['shipping_name']);
        }

        //收货地址判断
        $address=D('order')->get_my_address($user_id);
        if(!$address)return_data(50000,'收货地址为空');//去添加收货地址
        

          //计算快递费用
          $addr_ids=array(
              $address['country'],
              $address['province'],
              $address['city'],
              $address['district']
            );
           //收货区域
          $order['country']=$address['country'];
          $order['province']=$address['province'];
          $order['city']=$address['city'];
          $order['district']=$address['district'];
          $order['address']=$address['address'];
          $order['zipcode']=$address['zipcode'];
          $order['mobile']=$address['mobile'];
          $order['consignee']=$address['consignee'];
          $order['tel']=$address['tel'];
          $order['best_time']=$address['best_time'];

           $shipping_fee=0;
            

         /**********************一键购买***************开始****/
          $goods_id=I('post.id',0);
         
          if($goods_id)
          { 
             $attr_ids=I('post.attr_id','');
             $buy_num=I('post.buy_num',1);//属性集合

              if($attr_ids&&!is_array($attr_ids))
              {
                $attr_ids=explode(',', $attr_ids);
              }


             $goods = D('Goods')->get_goods_info($goods_id,$this->info);
            //库存判断
            if($goods['goods_number']<$buy_num)return_data(50001,'商品库存不足');

             $product_id=0;
             if($attr_ids)
             {
               $product_info = D('ProductsBase')->get_products_info($goods_id, $attr_ids);
               
               if($product_info)
               {
                $product_id=$product_info['product_id'];
                 //库存判断
                 if($product_info['product_number']<$buy_num)return_data(50002,'货品库存不足，请选择其他属性');
               }
             }

          //快递费用          
          if ($order['shipping_id'] > 0) {
            $region= $addr_ids;

            $shipping_info = D('order')->shipping_area_info($order['shipping_id'], $region);

            if (!empty($shipping_info)) {
                $shipping_fee = ($goods ['is_shipping'] == 1) ? 0 : shipping_fee($shipping_info['shipping_code'], $shipping_info['configure'], $goods['goods_weight']*$buy_num,  $goods ['goods_price']*$buy_num, $buy_num);

            }
           }

            $order['shipping_fee']=$shipping_fee;



             $spec_price = D('Goods')->spec_price($attr_ids);
             $goods_price = D('GoodsBase')->get_final_price($this->info,$goods_id, $buy_num, true, $attr_ids);


             $goods['market_price']=$goods['market_price_org']+$spec_price;
             
             $goods_attr = D('order')->get_goods_attr_info($attr_ids);
             $goods_attr_id = join(',', $attr_ids);
             /* 计算商品的佣金 */
             $profit_rate = D('Category')->get_cat_rate( $goods['cat_id']);
             $profit_rate =$profit_rate?$profit_rate:0;
            
             //总价
             $order['goods_amount']=$goods_price*$buy_num;
             $order['order_amount']=$goods_price*$buy_num+$shipping_fee;

                /* 检查红包是否存在 */
              if ($order ['bonus_id'] > 0) {
                  $bonus = D('Order')->bonus_info($user_id,$order ['bonus_id']);
              
                  if (empty($bonus) || $bonus ['user_id'] != $user_id || $bonus ['order_id'] > 0 || $bonus ['min_goods_amount'] >$order['order_amount']) {
                      $order ['bonus_id'] = 0;
                  }
              } elseif (isset($_POST ['bonus_sn'])) {
                  $bonus_sn = trim($_POST ['bonus_sn']);
                  $bonus = D('Order')->bonus_info($user_id,0, $bonus_sn);
                  $now = gmtime();
                  if (empty($bonus) || $bonus ['user_id'] > 0 || $bonus ['order_id'] > 0 || $bonus ['min_goods_amount'] >$order['order_amount'] || $now > $bonus ['use_end_date']) {
                      
                  } else {
                      if ($user_id > 0) {
                          $sql = "UPDATE " . C('DB_PREFIX') . "user_bonus SET user_id = '$user_id' WHERE bonus_id = '$bonus[bonus_id]' LIMIT 1";
                          M()->execute($sql);
                      }
                      $order ['bonus_id'] = $bonus ['bonus_id'];
                      $order ['bonus_sn'] = $bonus_sn;
                  }
              }
              if($order ['bonus_id'] > 0)
              {
                $bonus = D('Order')->bonus_info($user_id,$order ['bonus_id']);
                $order['order_amount']-=$bonus['type_money'];
                $order['bonus']=$bonus['type_money'];
              }


             
              /* 生成购物车数据 */
              $cart = array(
                  'user_id' => $user_id,
                  'session_id' => 0,
                  'goods_id' => $goods_id,
                  'goods_sn' => addslashes($goods['goods_sn']),
                  'product_id' => $product_id,
                  'goods_name' => addslashes($goods['name']),
                  'market_price' => $goods['market_price'],
                  'goods_attr' => addslashes($goods_attr),
                  'goods_attr_id' => $goods_attr_id,
                  'is_real' => $goods['is_real'],
                  'extension_code' => $goods['extension_code'],
                  'is_gift' => 0,
                  'is_shipping' => $goods['is_shipping'],
                  'rec_type' => 0,
                  'buy_type' => 2,
                  'profit_rate' => $profit_rate,
                  'goods_price' => $goods_price,
                  'goods_number' => $buy_num
              );
              $cart['commission']=0;
              if($profit_rate)
                 $cart['commission']=($profit_rate*$order['goods_amount'])/100;

                 /* 插入订单表 */
                $error_no = 0;
                do {               
                  $order_sn= get_order_sn(); // 获取新订单号
                  $status=M('order_info')->where("order_sn='$order_sn'")->getField('order_id');
                  if($status)$error_no=1062;
                  else $error_no=0;

                } while ($error_no == 1062); // 如果是订单号重复则重新提交数据



                $order ['order_sn'] =$order_sn;



                $commission=0;
                if($mshop_id)//有归属旅行社
                {
                    $order ['mshop_id'] = $mshop_id;

                    $commission=$cart['commission'];
                    $order ['commission']=$commission;
                }
                $M_order_info->startTrans();
                $M_order_info->create($order);
                $order_id=$M_order_info->add($order);



                if(!$order_id)return_data(10003,'订单插入失败');
                 /* 插入订单商品 */
                  $order_goods=$cart;
                  $order_goods['order_id']=$order_id;

                  $M_order_goods->create($order_goods);
                  $rec_id=$M_order_goods->add($order_goods);


                   //减库存
                   /* 检查：库存 */
                   $use_storage=M('shop_config')->where("code='use_storage'")->getField('value');
                   $stock_dec_time=M('shop_config')->where("code='stock_dec_time'")->getField('value');                    

                   $where=array();
                   $where['goods_id']=$goods_id;
                   if($use_storage==1&&$stock_dec_time==1)
                   {
                     $status1=$M_goods->where($where)->setDec('goods_number',$buy_num);                  
                   }
                   else $status1=1;

                     

                    //加销量
                    $status2=M('touch_goods')->where($where)->setInc('sales_volume',$buy_num);


                   if($order_id && $rec_id&&$status1){
                    //减货品库存
                    if($cart['product_id']&&$use_storage==1&&$stock_dec_time==1)
                    {
                      $where=array();
                      $where['product_id']=$cart['product_id'];
                      $status3=$M_products->where($where)->setDec('product_number',$buy_num);
                    }
                     //红包已使用
                     if ($order ['bonus_id'] > 0) {
                         D('Order')->use_bonus($order ['bonus_id'], $order_id);
                      }

                    $M_order_info->commit();//成功则提交



                     $rn_data=array();
                     $rn_data['order_id']=$order_id;

                     return_data(0,'订单生成成功',$rn_data);
                  }else{
                     $M_order_info->rollback();//不成功，则回滚
                     return_data(10003,'订单生成失败',$rn_data);
                  }

              // $cart['mshop_id']=$mshop_id;

              // print_r(STR_PAD_LEFT);exit();
          }
            /**********************一键购买***************结束****/
          else//购物车
          {
            $rec_ids=I('post.rec_ids',array());

              if($rec_ids&&!is_array($rec_ids))
              {
                $rec_ids=explode(',', $rec_ids);
              }
              

            /* 检查购物车中是否有商品 */
            if(!empty($rec_ids))
              $condition = "user_id = '" . $user_id . "' " . "AND parent_id = 0 AND is_gift = 0 AND rec_type = '$flow_type' AND rec_id ".db_create_in($rec_ids);
            else
              return_data(20002,'购物中没有商品');
           
            $count =M('cart')->where($condition)->count();

            
            if($count==0)
            {
              return_data(50003,'购物中没有商品');
            }

            // 取得商品列表，计算合计
            $cart_goods = D('Order')->cart_goods($this->info,$flow_type,$rec_ids);
            if(!$cart_goods)return_data(20002,'购物车读取不合法');

            /* 检查红包是否存在 */
            if ($order ['bonus_id'] > 0) {
                $bonus = D('Order')->bonus_info($user_id,$order ['bonus_id']);
                if (empty($bonus) || $bonus ['user_id'] != $user_id || $bonus ['order_id'] > 0 || $bonus ['min_goods_amount'] >D('Order')->cart_amount($rec_ids,true, $flow_type)) {
                    $order ['bonus_id'] = 0;
                } 
            } elseif (isset($_POST ['bonus_sn'])) {
                $bonus_sn = trim($_POST ['bonus_sn']);
                $bonus = D('Order')->bonus_info($user_id,0, $bonus_sn);
                $now = gmtime();

                if (empty($bonus) || $bonus ['user_id'] > 0 || $bonus ['order_id'] > 0 || $bonus ['min_goods_amount'] > D('order')->cart_amount($rec_ids,true, $flow_type) || $now > $bonus ['use_end_date']) {
                    
                } else {
                    if ($user_id > 0) {
                        $sql = "UPDATE " . C('DB_PREFIX') . "user_bonus SET user_id = '$user_id' WHERE bonus_id = '$bonus[bonus_id]' LIMIT 1";
                        M()->execute($sql);
                    }
                    $order ['bonus_id'] = $bonus ['bonus_id'];
                    $order ['bonus_sn'] = $bonus_sn;
                }
            }

            //计算订单的费用
            $total = D('Users')->order_fee($this->info,$order, $cart_goods, $address); 


            $order ['bonus'] = $total ['bonus']?$total ['bonus']:0;
            $order ['goods_amount'] = $total ['goods_price'];
            $order ['discount'] = $total ['discount'];
            $order ['surplus'] = $total ['surplus']?$total ['surplus']:0;
            $order ['tax'] = $total ['tax']?$total ['tax']:0;







            // 购物车中的商品能享受红包支付的总额
            // $discount_amout = D('Order')->compute_discount_amount($rec_ids);
            // // 红包和积分最多能支付的金额为商品总额
            // $temp_amout = $order ['goods_amount'] - $discount_amout;
            // if ($temp_amout <= 0) {
            //     $order ['bonus_id'] = 0;
            // }


             $order ['shipping_fee'] = $total ['shipping_fee'];
             $order ['insure_fee'] = $total ['shipping_insure'];


            /* 支付方式 */
            // if ($order ['pay_id'] > 0) {
            //     $payment = D('Order')->payment_info($order ['pay_id']);
            //     $order ['pay_name'] = addslashes($payment ['pay_name']);
            // }
            $order ['pay_fee'] = $total ['pay_fee'];
            $order ['cod_fee'] = $total ['cod_fee'];


            /* 如果订单金额为0（使用余额或积分或红包支付），修改订单状态为已确认、已付款 */
            $order ['order_amount'] = number_format($total ['amount'], 2, '.', '');

             if ($order ['order_amount'] <= 0) {
                $order ['confirm_time'] = gmtime();
                $order ['pay_time'] = gmtime();
                $order ['order_amount'] = 0;
            }
            //积分
            $order ['integral_money'] = $total ['integral_money'];
            $order ['integral'] = $total ['integral'];

              // if ($order ['extension_code'] == 'exchange_goods') {
              //     $order ['integral_money'] = 0;
              //     $order ['integral'] = $total ['exchange_integral'];
              // }

              /* 插入订单表 */
               $error_no = 0;
                do {               
                  $order_sn= get_order_sn(); // 获取新订单号
                  $status=M('order_info')->where("order_sn='$order_sn'")->getField('order_id');
                  if($status)$error_no=1062;
                  else $error_no=0;

                } while ($error_no == 1062); // 如果是订单号重复则重新提交数据


                $order ['order_sn'] =$order_sn;



                $commission=0;
                if($mshop_id)//有归属旅行社
                {
                    $order ['mshop_id'] = $mshop_id;

                    $sql="select sum(profit_rate*goods_price*goods_number)/100 as commission "
                    . " FROM " . C('DB_PREFIX'). "cart WHERE rec_id  " .db_create_in($rec_ids) . " AND rec_type = '$flow_type'";
                    $data_csn=M()->query($sql);
                    $commission=$data_csn[0]['commission']?$data_csn[0]['commission']:0;
                }
                $order ['commission']=$commission;

                // print_r($order);exit();

                $M_order_info->startTrans();

                $M_order_info->create($order); 
                $order_id=$M_order_info->add($order);



                if(!$order_id)return_data(10003,'订单插入失败');

                 /* 处理余额、积分、红包 */
                // if ($order ['user_id'] > 0 && $order ['surplus'] > 0) {
                //     D('ClipsBase')->log_account_change($order ['user_id'], $order ['surplus'] * (- 1), 0, 0, 0, '余额付款订单'.$order ['order_sn']);
                // }
                // if ($order ['user_id'] > 0 && $order ['integral'] > 0) {
                //     D('ClipsBase')->log_account_change($order ['user_id'], 0, 0, 0, $order ['integral'] * (- 1), '余额付款订单'.$order ['order_sn']);
                // }
                 if ($order ['bonus_id'] > 0) {
                     D('Order')->use_bonus($order ['bonus_id'], $order_id);

                  }

                /* 插入订单商品 */
                $sql = "INSERT INTO " .C('DB_PREFIX'). "order_goods( "
                        . "order_id, goods_id, goods_name, goods_sn, product_id, goods_number, market_price, " 
                       . "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id,commission) "
                       . " SELECT '$order_id', goods_id, goods_name, goods_sn, product_id, goods_number, market_price, "
                       . "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id ,(profit_rate*goods_price*goods_number/100) as commission"
                       . " FROM " . C('DB_PREFIX'). "cart WHERE rec_id " . db_create_in($rec_ids) . "  AND rec_type = '$flow_type'";



                 $status1=M()->execute($sql);

             if($order_id&&$status1>=1){
              /* 检查：库存 */
               $use_storage=M('shop_config')->where("code='use_storage'")->getField('value');
               $stock_dec_time=M('shop_config')->where("code='stock_dec_time'")->getField('value');
               if($use_storage==1&&$stock_dec_time==1)
                D('Order')->change_order_goods_storage($order_id, true,0);
               

                //对应清理购物车
                clear_cart($user_id,$rec_ids);

               $M_order_info->commit();//成功则提交

               $rn_data=array();
               $rn_data['order_id']=$order_id;

               return_data(0,'订单生成成功',$rn_data);
            }else{
               $M_order_info->rollback();//不成功，则回滚
               return_data(10003,'订单生成失败',$rn_data);
            }


            return_data(20002,'购物车功能开发中');
          }



    }

}